package com.ljx.rag.rag.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.ljx.rag.rag.domain.dto.OllamaChatResponse;
import com.ljx.rag.rag.domain.dto.OllamaEmbeddingReq;
import com.ljx.rag.rag.domain.dto.OllamaEmbeddingResponse;
import com.ljx.rag.rag.service.EmbeddingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2025-05-17  23:36
 */
@Service
public class EmbeddingServiceImpl implements EmbeddingService {
    @Autowired
    private WebClient webClient;

    @Value("${rag.ai.embedding.model}")
    private String model;

    @Override
    public List<BigDecimal> callEmbeddingApi(String prompt) {
        OllamaEmbeddingReq req = OllamaEmbeddingReq.builder()
                .model(model)
                .prompt(prompt)
                .build();

        OllamaEmbeddingResponse response = webClient.post()
                .uri("/api/embeddings")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .bodyValue(req)
                .retrieve()
                .bodyToMono(OllamaEmbeddingResponse.class)
                .block(); // 同步阻塞获取结果
        if (CollUtil.isEmpty(response.getEmbedding())) {
            return new ArrayList<>();
        }
        return response.getEmbedding();
    }



}
